
//
//  JJJOAuthViewController.swift
//  myBlog
//
//  Created by 姜军君 on 15/11/28.
//  Copyright © 2015年 JJJ. All rights reserved.
//

import UIKit
import SVProgressHUD

class JJJOAuthViewController: UIViewController, UIWebViewDelegate {

    lazy private var webView = UIWebView()
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        title = "JiangBlog"
        
        webView.delegate = self
        webView.loadRequest(NSURLRequest(URL: JJJNetworkTool.sharedTool.oauthURL()))
    }
    
    /// 关闭
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - 代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        if !urlString.hasPrefix("http://www.baidu.com/") {
            
            return true
        }
        
        if let query = request.URL?.query where query.hasPrefix("code=") {
            
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            // 换取TOKEN
            JJJNetworkTool.sharedTool.loadToken(code, finished: { (result, error) -> () in
                
                if result != nil && error == nil {
                    
                    let userAccount = JJJUserAccount(dict: result!)
                    // 保存账户信息
                    userAccount.saveUserAccount()
                    //加载用户信息
                    JJJNetworkTool.sharedTool.loadUserInfo(userAccount.uid!, finished: { (result, error) -> () in
                        print(result)
                    })
                }else {
                    
                    print(error)
                    SVProgressHUD.showInfoWithStatus("网络错误")
                    
                    // 延时关闭
                    let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
                    dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
                        self.close()
                    })
                }
                
             })
        }else {
            
            close()
        }
        
        return false
    }
}
